package com.uliky.shouyiLibrary.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.uliky.common.utils.R;
import com.uliky.shouyiLibrary.product.service.CategoryBrandRelationService;
import com.uliky.shouyiLibrary.product.vo.Catelog2Vo;
import com.sun.org.apache.bcel.internal.generic.LCONST;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.javassist.expr.NewArray;
import org.redisson.Redisson;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.uliky.common.utils.PageUtils;
import com.uliky.common.utils.Query;

import com.uliky.shouyiLibrary.product.dao.CategoryDao;
import com.uliky.shouyiLibrary.product.entity.CategoryEntity;
import com.uliky.shouyiLibrary.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );
        return new PageUtils(page);
    }

    /**
     * 查出所有分类
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //1级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        //

        //2.组装为父子结构

        return level1Menus;
    }

    /**
     * 批量删除
     *
     * @param list
     */
    @Override
    public void removeMenusByIds(List<Long> list) {
        //TODO 1.检查当前删除的菜单，是否被别的地方引用
        //一般逻辑删除

        baseMapper.deleteBatchIds(list);
    }

    /**
     * 找到catelog的完整路径
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();

        findParentPath(catelogId, paths);

        return (Long[]) paths.toArray(new Long[paths.size()]);
    }

    /**
     * 级联更新
     *
     * @param category
     */
    @Override

    @Caching(evict = {
            @CacheEvict(value ="category",key ="'getLevelCategorys'" ),
            @CacheEvict(value ="category",key ="'getCatalogJson'" )
    })
    @Transactional
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }
    /**
     * 查询二 三级信息(缓存) 使用注解
     *
     * @return
     */
    @Override
    @Cacheable(value = "category",key = "#root.methodName")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        /**
         * 将多次查询数据库变为一次
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        List<CategoryEntity> levelCategorys = getparent_cid(selectList, 0L);
        Map<String, List<Catelog2Vo>> parentCid = levelCategorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //每个一级分类下的二级分类
            List<CategoryEntity> categoryEntities = getparent_cid(selectList, v.getCatId());
            //封装数据
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(item -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, item.getCatId().toString(), item.getName());
                    //找三级分类
                    List<CategoryEntity> level3Catelog = getparent_cid(selectList, item.getCatId());
                    if (level3Catelog != null) {
                        //封装三级分类
                        List<Catelog2Vo.Category3Vo> category3VoList = level3Catelog.stream().map(l -> {
                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(item.getCatId().toString(), l.getCatId().toString(), l.getName());
                            return category3Vo;

                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(category3VoList);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return parentCid;
    }
    /**
     * 查询二 三级信息(缓存)
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJson2() {
        //查缓存
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            //查数据库 加锁，防止缓存击穿
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWtihRedissonLock();
            return catalogJsonFromDb;
        }
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;
    }

    /**
     * 查询二 三级信息（数据库）分布式锁 redisson实现
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWtihRedissonLock() {
        //使用redisson实现分布式锁
        //锁的名字->粒度选择，
        RLock lock = redisson.getLock("catalog-lock");
        lock.lock();
        //加锁成功
        Map<String, List<Catelog2Vo>> dataFromDb;
        try {
            dataFromDb = getDataFromDb();
        } finally {
            lock.unlock();
        }
        return dataFromDb;
    }

    /**
     * 查询二 三级信息（数据库）分布式锁 redis实现
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWtihRedisLock() {
        ///uuid
        String uuid = UUID.randomUUID().toString();
        //1.分布式锁
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            //加锁成功
            Map<String, List<Catelog2Vo>> dataFromDb;
            try {
                dataFromDb = getDataFromDb();
            } finally {
                //查删锁
                String lua = "if redis.call('get',KEY[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(lua, Long.class), Arrays.asList("lock"), uuid);

            }
            //必须为原子操作---》lua脚本
//            if(uuid.equals(redisTemplate.opsForValue().get("lock"))) {
//                redisTemplate.delete("lock");
//            }
            //redisTemplate.delete("lock");
            return dataFromDb;
        } else {
            //加锁失败
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDbWtihRedisLock(); //自旋重试
        }

    }

    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }
        /**
         * 将多次查询数据库变为一次
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        List<CategoryEntity> levelCategorys = getparent_cid(selectList, 0L);
        Map<String, List<Catelog2Vo>> parentCid = levelCategorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //每个一级分类下的二级分类
            List<CategoryEntity> categoryEntities = getparent_cid(selectList, v.getCatId());
            //封装数据
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(item -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, item.getCatId().toString(), item.getName());
                    //找三级分类
                    List<CategoryEntity> level3Catelog = getparent_cid(selectList, item.getCatId());
                    if (level3Catelog != null) {
                        //封装三级分类
                        List<Catelog2Vo.Category3Vo> category3VoList = level3Catelog.stream().map(l -> {
                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(item.getCatId().toString(), l.getCatId().toString(), l.getName());
                            return category3Vo;

                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(category3VoList);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        //存入缓存
        String s = JSON.toJSONString(parentCid);
        redisTemplate.opsForValue().set("catalogJSON", s, 1, TimeUnit.DAYS);
        return parentCid;
    }

    /**
     * 查询二 三级信息（数据库） 本地锁
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithLocalLock() {
        synchronized (this) {
            return getDataFromDb();
        }
    }

    private List<CategoryEntity> getparent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        //return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid",parent_cid));
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
    }

    /**
     * 得到一级分类
     */
    @Override
    @Cacheable(value = {"category"},key = "#root.method.name")
    public List<CategoryEntity> getLevelCategorys() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    private void findParentPath(Long catelogId, List<Long> paths) {

        CategoryEntity category = this.getById(catelogId);
        if (category.getParentCid() != 0) {
            findParentPath(category.getParentCid(), paths);
        }
        paths.add(catelogId);
    }

    /**
     * 递归查找在所有分类中找自己的子分类
     *
     * @param root 当前类型
     * @param all  所有分类
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream()
                .filter(categoryEntity ->
                        categoryEntity.getParentCid() == root.getCatId())
                .map(categoryEntity -> {
                    //递归找子菜单
                    categoryEntity.setChildren(getChildrens(categoryEntity, all));
                    return categoryEntity;
                })
                .sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList());
        return children;
    }

}